<template>
  <div class="app-container">
    <el-form
      class="searchform"
      ref="queryParams"
      :model="queryParams"
      size="small"
      :inline="true"
    >
      <el-form-item label="领用人">
        <user-select v-model="queryParams.applyUserId"></user-select>
      </el-form-item>
      <el-form-item label="领用时间">
        <my-time-picker
          style="width: 300px"
          :start-time.sync="queryParams.applyStartTime"
          :end-time.sync="queryParams.applyEndTime"
        ></my-time-picker>
      </el-form-item>
      <el-form-item label="归还时间">
        <my-time-picker
          style="width: 300px"
          :start-time.sync="queryParams.returnStartTime"
          :end-time.sync="queryParams.returnEndTime"
        ></my-time-picker>
      </el-form-item>
      <el-form-item label="归还人">
        <user-select v-model="queryParams.returnUserId"></user-select>
      </el-form-item>
      <el-form-item label=" " label-width="20px">
        <el-button type="primary" icon="el-icon-search" @click="getList"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-wrapper">
      <div
        class="tableoperation"
        style="display: flex; justify-content: space-between"
      >
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
          "
        >
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click.native.prevent="openDialog({}, 'add')"
              >添加</el-button
            >
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </div>
          <div style="margin-left: auto">
            <el-button
              type="warning"
              plain
              icon="el-icon-printer"
              size="mini"
              @click.native.prevent="handlePrint"
              v-if="equipmentId"
              :disabled="dataList.length == 0"
              >打印</el-button
            >
          </div>
        </div>

        <print
          :title="title"
          :disabled="dataList.length == 0"
          ref="print"
          :beforeMethod="getPrintList"
          :auto-print="false"
          :showPrintBtn="false"
        >
          <table
            style="width: 100%"
            border="1"
            cellspacing="0"
            cellpadding="0"
            align="center"
          >
            <tr>
              <td>发布日期</td>
              <td>{{ now | formatDate }}</td>
              <td>实施日期</td>
              <td>{{ now | formatDate }}</td>
            </tr>
          </table>
          <table
            style="width: 100%; margin-top: -2px"
            border="1"
            cellspacing="0"
            cellpadding="0"
            align="center"
          >
            <thead>
              <tr>
                <td>领用日期</td>
                <td>领用人</td>
                <td>仪器设备型号及编号</td>
                <td>归还日期</td>
                <td>归还人</td>
                <td>归还状态</td>
                <td>保管人<br />确认签字</td>
              </tr>
            </thead>
            <tbody v-for="(item, index) in printList" :key="index">
              <tr v-for="(trItem, trIndex) in item.instrument" :key="trIndex">
                <td v-if="trIndex == 0" :rowspan="item.instrument.length">
                  {{ new Date(item.applyTime) | formatDate }}
                </td>
                <td v-if="trIndex == 0" :rowspan="item.instrument.length">
                  {{ item.applyUserName }}
                </td>
                <td>
                  {{ trItem.equipmentName }}({{ trItem.equipmentNumber }})
                  <span v-if="item.returnState == 1"
                    >({{ trItem.return ? "已归还" : "未归还" }})</span
                  >
                </td>
                <td v-if="trIndex == 0" :rowspan="item.instrument.length">
                  {{
                    item.returnTime
                      ? new Date(item.returnTime)
                      : null | formatDate
                  }}
                </td>
                <td v-if="trIndex == 0" :rowspan="item.instrument.length">
                  {{ item.returnUserName }}
                </td>
                <td v-if="trIndex == 0" :rowspan="item.instrument.length">
                  {{
                    item.returnState == 0
                      ? "未归还"
                      : item.returnState == 1
                      ? "部分归还"
                      : "已归还"
                  }}
                </td>
                <td v-if="trIndex == 0" :rowspan="item.instrument.length">
                  <oss-image
                    v-if="item.managementSignOssId"
                    :oss-id="item.managementSignOssId"
                    @load="imgSuccess"
                    @error="imgSuccess"
                    style="height: 8mm"
                  ></oss-image>
                </td>
              </tr>
            </tbody>
          </table>
        </print>
      </div>

      <el-table
        v-loading="loading"
        :data="dataList"
        @row-dblclick="(row) => openDialog(row, 'view')"
      >
        <el-table-column
          prop="applySubjectMatter"
          label="领用事由"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.applySubjectMatter }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="applyTime"
          label="领用日期"
          align="center"
          min-width="160"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.applyTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="outEquipmentStatus"
          label="出库设备状态"
          align="center"
          min-width="100"
        >
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.outEquipmentStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="NORMAL"
              @change="changeState(row, 'outEquipmentStatus')"
              inactive-value="DAMAGE"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="applyUserName"
          label="领用人签字"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.applyUserName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="returnTime"
          label="归还日期"
          align="center"
          min-width="160"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.returnTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="storeEquipmentStatus"
          label="入库设备状态"
          align="center"
          min-width="100"
        >
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.storeEquipmentStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="NORMAL"
              @change="changeState(row, 'storeEquipmentStatus')"
              inactive-value="DAMAGE"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="returnUserName"
          label="归还人签字"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.returnUserName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="managementUserName"
          label="管理员签字"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.managementUserName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="{ row }">
            <el-link
              type="primary"
              v-show="row.returnState != 2"
              @click.native.prevent="openDialog(row, 'return')"
              style="margin-right: 10px"
              >归还</el-link
            >
            <el-link type="danger" @click.native.prevent="handleDelete(row)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <div style="width: 100%; height: 50px">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="page.pageNum"
          :limit.sync="page.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <giveBackDialog ref="dialog" @close="getList"></giveBackDialog>
  </div>
</template>

<script>
import {
  list,
  remove,
  updateState,
  generateWarehousingRecords,
} from "@/api/resourse/giveBack";
import giveBackDialog from "./components/giveBackDialog";
import { eq } from "lodash";

export default {
  name: "GiveBackList",
  components: { giveBackDialog },
  props: {
    equipmentId: {
      type: String,
      default: undefined,
    },
  },
  data() {
    return {
      now: new Date(),
      dataList: [],
      loading: false,
      total: 0,
      queryParams: {},
      queryParamsCache: {
        applyUserName: null, //领用人名称
        applyStartTime: null, //领用开始时间
        applyEndTime: null, //领用结束时间
        returnUserName: null, //归还人名称
        returnStartTime: null, //归还开始时间
        returnEndTime: null, //归还结束时间
      },
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      printList: [],
      title: "现场仪器设备领用归还登记表",
      printReady: null,
    };
  },
  filters: {
    formatDate(val) {
      if (val)
        return (
          val.getFullYear() +
          "年" +
          val.getMonth() +
          1 +
          "月" +
          val.getDate() +
          "日"
        );
      return null;
    },
  },
  created() {
    this.init();
  },
  watch: {
    equipmentId(val) {
      if (val) {
        this.getList();
      }
    },
  },
  methods: {
    changeState(row, field) {
      let warehousingType = "";
      let warehousingStatus = row[field];
      if (field === "outEquipmentStatus") {
        warehousingType = "OUT";
      } else if (field === "storeEquipmentStatus") {
        warehousingType = "STORE";
      }
      updateState({ id: row.id, warehousingType, warehousingStatus });
    },
    imgSuccess() {
      clearTimeout(this.printReady);
      this.printReady = setTimeout(() => {
        this.$nextTick(() => {
          this.$refs.print.printPreview();
        });
      }, 100);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "warehousing/equipmentWarehousing/export",
        {
          ...this.queryParams,
          pageNum: 1,
          pageSize: this.total,
        },
        `${this.title}_${new Date().getTime()}.xlsx`
      );
    },
    init() {
      this.reset();
    },
    handleDelete(row) {
      this.$confirm("确认删除这条记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          remove(row.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    getList() {
      this.loading = true;
      list({ ...this.queryParams, ...this.page, equipmentId: this.equipmentId })
        .then((res) => {
          this.dataList = res.rows;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async getPrintList() {
      let res = await list({
        ...this.queryParams,
        pageNum: 1,
        pageSize: this.total,
      });
      this.printList = res.rows.reduce((pre, cur) => {
        cur.instrument = JSON.parse(cur.instrument);
        pre.push(cur);
        return pre;
      }, []);
      this.imgSuccess();
    },
    reset() {
      this.queryParams = JSON.parse(JSON.stringify(this.queryParamsCache));
      this.getList();
    },
    openDialog(row, type) {
      this.$refs.dialog.open(row.id, type);
    },
    handlePrint() {
      generateWarehousingRecords({
        ...this.queryParams,
        equipmentId: this.equipmentId,
      })
        .then((res) => {
          if (res.msg) window.open(res.msg);
        })
        .catch((err) => {});
    },
  },
};
</script>

<style>
table {
  text-align: center;
}
</style>
